    //
//  LessonPickerViewController.m
//  Cachalot
//
//  Created by Adam Cue on 4/21/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LessonPickerViewController.h"
#import "LessonPreviewGridViewCell.h"
#import "LessonViewController.h"
#import "JSON.h"

#define SHOW_CLASSES_BUTTON_FRAME   CGRectMake(0, 254, 32, 192)
#define GRID_VIEW_CELL_FRAME        CGRectMake(15, 0, 256, 277)
#define GRID_VIEW_CELL_SIZE         CGSizeMake(256, 277)

static dispatch_queue_t lessonPickerQueue;

@interface LessonPickerViewController (Private)
#pragma mark SetupMethods
- (void)setupGridView;
- (void)setupClassTable;
- (void)setupButtons;
- (void)setupNetworking;

#pragma mark HelperMethods
- (void)checkNetworkStatus:(NSNotification *)notice;
- (void)startLoading;
- (void)loadLessons:(NSString *)jsonString;

#pragma mark UserActions
- (void)refresh;
- (void)oldClasses:(id)sender;
@end

@implementation LessonPickerViewController

@synthesize lessons = _lessons;
@synthesize classTable = _classTable;
@synthesize showClassesButton = _showClassesButton;
@synthesize reach = _reach;
@synthesize gridView = _gridView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
   if (self) {
      if(!lessonPickerQueue) lessonPickerQueue = dispatch_queue_create("com.Cachalot.LessonPicker", NULL);
      firstRun = YES;
		internetAvailable = YES;
      firstLoad = YES;
   }
   return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	self.view.backgroundColor = [UIColor blackColor];
	UIImageView * backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"grid_background"]] autorelease];
   backgroundView.alpha = 0.3;
   [self.view addSubview:backgroundView];
   [self setupGridView];
   [self setupClassTable];
	[self setupButtons];
   [self setupNetworking];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
   return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

- (void)viewDidUnload {
	[super viewDidUnload];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
   self.reach = nil;
}


- (void)dealloc {
	self.lessons = nil;
   self.classTable = nil;
   self.showClassesButton = nil;
   self.reach = nil;
   self.gridView = nil;
   
   [super dealloc];
}

#pragma mark SetupMethods
- (void)setupGridView {
   _gridView = [[AQGridView alloc] initWithFrame:CGRectMake(0, 0, 1024, 660)];
   self.gridView.backgroundColor = [UIColor clearColor];
   self.gridView.opaque = NO;
   self.gridView.dataSource = self;
   self.gridView.delegate = self;
   UIView *clearView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)] autorelease];
   clearView.backgroundColor = [UIColor clearColor];
   self.gridView.gridHeaderView = clearView;
   self.gridView.leftContentInset = 15.0;
   self.gridView.rightContentInset = 15.0;
   [self.view addSubview:self.gridView];
}

- (void)setupClassTable {
	_classTable = [[ClassReadingsTableViewController alloc] initWithStyle:UITableViewStylePlain];
	self.classTable.forLessons = YES;
	self.classTable.delegate = self;
	self.classTable.tableView.frame = CGRectMake(-320, 0, 320, 704);
	self.classTable.tableView.separatorColor = [UIColor darkGrayColor];
	self.classTable.tableView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.84];
	self.classTable.tableView.hidden = YES;
	[self.view addSubview:self.classTable.tableView];
}

- (void)setupButtons {
   _showClassesButton = [UIButton buttonWithType:UIButtonTypeCustom];
	self.showClassesButton.frame = SHOW_CLASSES_BUTTON_FRAME;
	[self.showClassesButton setImage:[UIImage imageNamed:@"classes_pullout"] forState:UIControlStateNormal];
	[self.showClassesButton addTarget:self action:@selector(oldClasses:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:self.showClassesButton];
   
   UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)];
	self.navigationItem.rightBarButtonItem = refreshButton;
	[refreshButton release];
}

- (void)setupNetworking {
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
	_reach = [[Reachability reachabilityWithHostName:@"seamonster.ml.duke.edu"] retain];
	[self.reach startNotifier];
}

#pragma mark UserActions
- (void)refresh{
	if(internetAvailable == NO){
		UIAlertView *noInternetAlert = [[[UIAlertView alloc] initWithTitle:@"Connection required!" message:@"Could not download latest class' lessons.  Check back when you have an internet connection." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
		[noInternetAlert show];
		return;
	}
	[DSBezelActivityView newActivityViewForView:self.view withLabel:@"Loading Lessons"];
	[self loadLessons:nil];
}

- (void)oldClasses:(id)sender{
	if(firstRun) self.classTable.tableView.frame = CGRectMake(-320, 0, 320, 704);
	firstRun = NO;
	[UIView animateWithDuration:0.8 delay:0.0 options:UIViewAnimationCurveLinear 
                    animations:^{
                       self.classTable.tableView.hidden = NO;
                       if(self.classTable.tableView.left < 0){
                          self.showClassesButton.left = 319;
                          self.classTable.tableView.left = 0;
                          [self.showClassesButton setImage:[UIImage imageNamed:@"Hide_Pullout"] forState:UIControlStateNormal];
                       }
                       else{
                          self.showClassesButton.left = -1;
                          self.classTable.tableView.right = 0;
                          [self.showClassesButton setImage:[UIImage imageNamed:@"classes_pullout"] forState:UIControlStateNormal];
                       }
                    }completion:nil];
}

#pragma mark HelperMethods
- (void)checkNetworkStatus:(NSNotification *)notice{
	NetworkStatus internetStatus = [self.reach currentReachabilityStatus];
	switch (internetStatus){
		case NotReachable:{
			internetAvailable = NO;
			break;
		}
		case ReachableViaWiFi:{
			internetAvailable = YES;
			[self.classTable loadClassList];
			break;
		}
		case ReachableViaWWAN:{
			internetAvailable = YES;
			[self.classTable loadClassList];
			break;
			
		}
	}
	if(firstLoad == YES){
      [DSBezelActivityView newActivityViewForView:self.view withLabel:@"Loading Lessons..."];
      dispatch_async(lessonPickerQueue, ^{
         [self loadLessons:nil];
      });
	}
	firstLoad = NO;
}

- (void)startLoading{
	[DSBezelActivityView newActivityViewForView:self.view withLabel:@"Loading Lessons..." width:160];
	[UIView animateWithDuration:0.8 delay:0.0 options:UIViewAnimationCurveLinear 
                    animations:^{
                       self.showClassesButton.left = -1;
                       self.classTable.tableView.right = 0;
                       [self.showClassesButton setImage:[UIImage imageNamed:@"classes_pullout"] forState:UIControlStateNormal];
                    } completion:nil];
}

- (void)loadLessons:(NSString *)jsonString{
	if(internetAvailable == NO){
		self.title = @"Lessons";
		UIAlertView *noInternetAlert = [[[UIAlertView alloc] initWithTitle:@"Connection required!" message:@"Could not download latest class' lessons.  Check back when you have an internet connection." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
		[noInternetAlert show];
		return;
	}
	internetAvailable = YES;
	if(jsonString == nil){
		jsonString = [[[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:NEW_LESSON_URL]] encoding:NSUTF8StringEncoding] autorelease];
	}
	if(self.classTable.listOfClasses){
		[self.classTable loadClassList];
	}
	NSDictionary *classInfo = [jsonString JSONValue];
	classID = [[classInfo objectForKey:@"id"] intValue];
	if([classInfo objectForKey:@"lessons"] != [NSNull null]){
		self.lessons = [classInfo objectForKey:@"lessons"];
	}
	else{
		self.lessons = nil;
	}
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateFormat:@"yyyy-MM-dd"];
	NSDate *date = [dateFormatter dateFromString:[classInfo objectForKey:@"date"]];
	[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
   dispatch_async(dispatch_get_main_queue(), ^{
      self.title = [NSString stringWithFormat:@"%@ - %@", [classInfo objectForKey:@"name"], [dateFormatter stringFromDate:date]];
      self.navigationController.tabBarItem = [[[UITabBarItem alloc] initWithTitle:@"Lessons" image:[UIImage imageNamed:@"lessons_tab"] tag:0] autorelease];
      [self.gridView reloadData];
      [DSBezelActivityView removeViewAnimated:YES];
   });
	[dateFormatter release];
}

#pragma mark AQGridViewDataSource
- (NSUInteger)numberOfItemsInGridView:(AQGridView *)gridView{
	return [self.lessons count];
}

- (AQGridViewCell *)gridView:(AQGridView *)gridView cellForItemAtIndex:(NSUInteger)index {
	static NSString * ReadingCellIdentifier = @"LessonCellIdentifier";
	LessonPreviewGridViewCell *cell = (LessonPreviewGridViewCell *)[self.gridView dequeueReusableCellWithIdentifier:ReadingCellIdentifier];
	if(cell == nil){
      cell = [[[LessonPreviewGridViewCell alloc] initWithFrame:GRID_VIEW_CELL_FRAME reuseIdentifier:ReadingCellIdentifier andSuperViewController:self] autorelease];
   }
	[LessonPreviewGridViewCell fillCell:cell forLesson:[self.lessons objectAtIndex:index] atIndex:index];													  
	return cell;
}

- (CGSize)portraitGridCellSizeForGridView:(AQGridView *)gridView {
	return GRID_VIEW_CELL_SIZE;
}

#pragma mark AQGridView Delegate
- (void)gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index {
}

#pragma mark LessonPreviewViewDelegate
- (void)selected:(int)index withImage:(UIImage *)selectedImage{
	int lessonID = [[[self.lessons objectAtIndex:index] objectForKey:@"id"] intValue];
	LessonViewController *lessonVC = [[LessonViewController alloc] initWithNibName:@"LessonViewController" bundle:[NSBundle mainBundle] lessonURL:[NSString stringWithFormat:LESSON_VIEW_URL, classID, lessonID] name:[[self.lessons objectAtIndex:index] objectForKey:@"name"] thumb:selectedImage];
	lessonVC.title = [[self.lessons objectAtIndex:index] objectForKey:@"name"];
	lessonVC.lessonID = lessonID;
	[self.navigationController pushViewController:lessonVC animated:YES];
	[lessonVC release];
}

- (void)deleted:(int)index{
  
}

#pragma mark ClassReadingsTableViewControllerDelegate
- (void)classClicked:(int)classIdClicked{
	if(classIdClicked == -1) return;
	[self startLoading];
   dispatch_async(lessonPickerQueue, ^{
      NSString *jsonString = [[[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:PARTICULAR_LESSONS_URL, classIdClicked]]] encoding:NSUTF8StringEncoding] autorelease];
      [self loadLessons:jsonString];
   });
}

@end
